# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : bodyRig_editor.py
# Date      : 2018/11/6
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------


__author__ = "lin lingwei"


import traceback

import maya.OpenMaya as om
import maya.cmds as mc

import configs.constants.body_constant as bc
import configs.constants.nodeType_constant as nc
import configs.constants.suffix_constant as sc

import scripts.commonCmds as con
import scripts.curveCmds as crc

import editors.editor as editor

import rig.body.bodyTemplate as bTemp
reload(bTemp)
# import rig.body.bodyCore as bCore
# reload(bCore)
import rig.body.arm as aRig
import rig.body.leg as lRig
import rig.body.spine as sRig
import rig.body.neck as nRig
import rig.body.finger as fRig



__version__ = "1.1.1"
class BodyRigEditor(object):
	
	def __init__(self):
		pass

	def editor(self):
		winName = "BodyRigEditor"
		winTitle = " - BodyRig Eidtor - V{}".format(__version__)
		editor.Editor().isExist(winName)
		win = mc.window(winName,t=winTitle,wh=[400,600],s=False, mxb=False, te=100)
		
		self.mainMenu()
		
		self.mainLayout()
		mc.showWindow(win)
		
		return
	
	def mainMenu(self):
		mbl = mc.menuBarLayout()
		mc.menu(l='File')
		mc.menuItem(l="Refresh Include",c=lambda *args:self.btn_refreshInclude())
		return
	def btn_refreshInclude(self):
		# import constant ;reload(constant)
		# import rig.body.bConstant as bc;reload(bc)
		# import cores.commonCore as con ;reload(con)
		return
	def mainLayout(self):
		form = mc.formLayout()
		tabs = mc.tabLayout()
		part = self.partLayout()
		auto = self.autoLayout()
		mc.setParent("..")
		ver = editor.Editor().copyright()
		
		mc.tabLayout(tabs, edit=True, tabLabel=((auto, "Auto ..."),(part, 'Part ...'),
												),
					 sti=2)
		mc.formLayout(form,e=True,
					  attachForm=[(tabs, 'top', 0), (tabs, 'left', 0), (tabs, 'right', 05),
								  (ver, 'bottom', 5), (ver, 'right', 5), (ver, 'left', 5)],
					  attachControl=[(tabs, 'bottom', 5, ver)
									 ],

					  # attachPosition=[(tree, 'right', 5, 75), (cmdslist, 'left', 0, 75)],
					  )
		return
	def partLayout(self):
		
		scoll = mc.scrollLayout(vst=0)
		
		column = mc.columnLayout(adj=True,p=scoll,w=388)
		mc.button(l="Import Global Control",c=lambda *args:bCore.BodyCore().init() )
		mc.separator(h=5)
		
		
		# -- arm
		mc.frameLayout(l=" - Arm Template ",cll=True,cl=True)
		mc.columnLayout(adj=True)
		
		arow = mc.rowLayout(nc=10)
		armPtfd = mc.textFieldGrp(l="Prefix : ",tx="def",w=195,adj=2,cw=(1,50))
		armMode = mc.optionMenu(l="Mode:",w=185,)
		mc.menuItem(l="Shoulder")
		mc.menuItem(l="Not Shoulder")
		mc.setParent('..')

		mc.button(l="Import Arm Template",c=lambda *args:self.btn_importArmTemp(armPtfd,armMode))
		mc.separator(h=5)
		
		mc.rowLayout(nc=10)
		
		armMir = mc.checkBox(l=" Mirror",v=1)
		armTwist = mc.checkBox(l=" Twist" , v=1)
		mc.text("    |    Mode :")
		acMode = mc.radioButtonGrp( labelArray3=['Ik', 'Fk', 'IkFk'],
									numberOfRadioButtons=3,sl=1,cw3=[50,50,50])
		mc.setParent('..')
		
		mc.separator(h=5)
		mc.button(l="Create Rig",c=lambda *args:self.btn_createArm(armPtfd,armMode,acMode,armMir,armTwist))
		mc.setParent("..")
		mc.setParent("..")
		
		
		# -- leg
		
		mc.frameLayout(l=" - Leg Template ",cll=True,cl=True)
		mc.columnLayout(adj=True)
		
		lrow = mc.rowLayout(nc=10)
		legPtfd = mc.textFieldGrp(l="Prefix : ",tx="def",w=195,adj=2,cw=(1,50))
		legMode = mc.optionMenu(l="Mode:",w=185,)
		mc.menuItem(l="Thigh")
		mc.menuItem(l="Not Thigh")
		mc.setParent('..')
		
		mc.button(l="Import Leg Template",c=lambda *args:self.btn_importLegTemp(legPtfd,legMode))
		mc.separator(h=5)

		mc.rowLayout(nc=10)

		legMir = mc.checkBox(l=" Mirror", v=1)
		legTwist = mc.checkBox(l=" Twist", v=1)
		mc.text("    |    Mode :")
		lcMode = mc.radioButtonGrp(labelArray3=['Ik', 'Fk', 'IkFk'],
								   numberOfRadioButtons=3, sl=1, cw3=[50, 50, 50])
		mc.setParent('..')

		mc.separator(h=5)
		mc.button(l="Create Rig",c=lambda *args:self.btn_createLeg(legPtfd,legMode,lcMode,legMir,legTwist))
		mc.setParent("..")
		mc.setParent("..")
		
		
		# -- spine
		mc.frameLayout(l=" - Spine Template ",cll=True,cl=True)
		mc.columnLayout(adj=True)
		
		arow = mc.rowLayout(nc=10)
		spinePtfd = mc.textFieldGrp(l="Prefix : ", tx="def", w=195, adj=2, cw=(1, 50))
		sMode = mc.optionMenu(l="Mode:", w=185, )
		mc.menuItem(l="Crv Fk")
		mc.menuItem(l="Sample Fk")
		mc.menuItem(l="Nurbs Fk")
		mc.setParent('..')
		
		mc.separator()
		sintsj = mc.intSliderGrp(l="Skin joint",f=True,v=10)
		sintcs = mc.intSliderGrp(l="control span", f=True,v=5)
		mc.button(l="Import Spine Template",c=lambda *args:self.btn_importSpineTemp(spinePtfd))
		mc.button(l="Refresh Spine Template",c=lambda *args:self.btn_refreshSpineTemp(spinePtfd,sintsj,sintcs))
		mc.button(l="Create Rig",c=lambda *args:self.btn_createSpine(spinePtfd,sMode,sintsj))
		mc.setParent("..")
		mc.setParent("..")
		
		mc.frameLayout(l=" - Neck Template ",cll=True,cl=True)
		mc.columnLayout(adj=True)
		
		arow = mc.rowLayout(nc=10)
		nPtfd = mc.textFieldGrp(l="Prefix : ", tx="def", w=195, adj=2, cw=(1, 50))
		nMode = mc.optionMenu(l="Mode:", w=185, )
		mc.menuItem(l="Crv Fk")
		mc.menuItem(l="Sample Fk")
		mc.menuItem(l="Nurbs Fk")
		mc.setParent('..')
		
		mc.separator()
		nintsj = mc.intSliderGrp(l="Skin joint",f=True,v=5)
		nintcs = mc.intSliderGrp(l="control span", f=True,v=3)
		mc.button(l="Import Neck Template",c=lambda *args:self.btn_importNeckTemp(nPtfd))
		mc.button(l="Refresh Neck Template",c=lambda *args:self.btn_refreshNeckTemp(nPtfd,nintsj,nintcs))
		mc.button(l="Create Rig",c=lambda *args:self.btn_createNeck(nPtfd,nMode,nintsj))
		mc.setParent("..")
		mc.setParent("..")

		mc.frameLayout(l=" - Finger Template ", cll=True, cl=False)
		mc.columnLayout(adj=True)

		arow = mc.rowLayout(nc=10)
		fPtfd = mc.textFieldGrp(l="Prefix : ", tx="def", w=195, adj=2, cw=(1, 50))
		fMode = mc.optionMenu(l="Mode:", w=185, )
		mc.menuItem(l="Sample Fk")
		mc.setParent('..')
		mc.separator()
		
		frow = mc.rowLayout(nc=10)
		mc.text("Hand Finger Tag :",w=100)
		mc.gridLayout(nc=3,cw=100,ch=20)
		
		checklist = [mc.checkBox(l=k,v=1) for k in [bc.gThumb,bc.gIndex,bc.gMiddle,bc.gRing,bc.gPinky]]
		
		mc.setParent("..")
		mc.setParent("..")
		mc.separator()

		mc.button(l="Import Hand Finger Template", c=lambda *args: self.btn_importFingerTemplate(fPtfd,checklist))
		mc.button(l="Create Rig", c=lambda *args: self.btn_createFingger(checklist, fMode,))

		mc.separator()

		trow = mc.rowLayout(nc=10)
		mc.text(" Toe Finger Tag :",w=100)
		mc.gridLayout(nc=3, cw=100, ch=20)

		tchecklist = [mc.checkBox(l=k,v=1) for k in [bc.gThumb,bc.gIndex,bc.gMiddle,bc.gRing,bc.gPinky]]

		mc.setParent("..")
		mc.setParent("..")
		mc.separator()

		mc.button(l="Import Toe Finger Template", c=lambda *args: self.btn_importFingerTemplate(fPtfd,tchecklist,toe=True))
		mc.button(l="Create Rig", c=lambda *args: self.btn_createFingger(tchecklist, fMode,toe=True))
		mc.setParent("..")
		mc.setParent("..")
		
		
		mc.setParent("..")
		mc.setParent("..")

		return scoll
	def btn_importArmTemp(self,prefixTfd,mode):
		reload(bTemp)
		prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		m = mc.optionMenu(mode,q=True,sl=True)
		if m == 1:
			bTemp.importArmTemplate(prefix)
		elif m == 2:
			bTemp.importArmTemplate(prefix,False)
		return
	def btn_createArm(self,prefixTfd,tmpMode=0,cteMode=0,mirCheck=0,TwiCheck=0):
		
		if tmpMode:
			sm = mc.optionMenu(tmpMode, q=True, sl=True)
			if sm == 1: sa = True
			elif sm == 2: sa = False
		if cteMode:
			cm = mc.radioButtonGrp(cteMode, q=True, sl=True)
			if cm == 1: armMode = 'ik'
			elif cm == 2: armMode = 'fk'
			elif cm == 3: armMode = 'ikfk'
		if mirCheck:
			mm = mc.checkBox(mirCheck,q=True,v=True)
		if TwiCheck:
			tm = mc.checkBox(TwiCheck,q=True,v=True)
		prefix = prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)

		reload(aRig)
		tmpdata = aRig.Arm(prefix,).getTemplateDate()
		# for tmp in tmpdata:
		try:
			make = tmpdata["make"]
			if make == "def":
				make = ""
			print "# --- %s"%make
			# print( "# -- left")
			aobj = aRig.Arm(make)
			aobj.create()
			aobj.create(1)
			return aobj
			# if mm:
			# 	print("# -- right")
			#
			# 	aRig.Arm(make, gRight).create2(tmp,armMode=armMode,mirror=True,twist=tm,shoulder=sa)
			#
			# aRig.Arm("","L").create()
			# aRig.Arm("","R").create(mirror=True)
		except:
			traceback.print_exc()
		return
	def btn_importLegTemp(self,prefixTfd,mode):
		reload(bTemp)
		prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		m = mc.optionMenu(mode,q=True,sl=True)
		if m == 1:
			bTemp.importLegTemplate(prefix)
		elif m == 2:
			bTemp.importLegTemplate(prefix,False)
		return
	def btn_createLeg(self,prefixTfd,tmpMode=0,cteMode=0,mirCheck=0,TwiCheck=0):
		
		if tmpMode:
			sm = mc.optionMenu(tmpMode, q=True, sl=True)
			if sm == 1: sa = True
			elif sm == 2: sa = False
		if cteMode:
			cm = mc.radioButtonGrp(cteMode, q=True, sl=True)
			if cm == 1: armMode = 'ik'
			elif cm == 2: armMode = 'fk'
			elif cm == 3: armMode = 'ikfk'
		if mirCheck:
			mm = mc.checkBox(mirCheck, q=True, v=True)
		if TwiCheck:
			tm = mc.checkBox(TwiCheck, q=True, v=True)
		prefix = prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)

		reload(lRig)
		tmpdata = lRig.Leg(prefix,).getTemplateDate()

		try:
			make = tmpdata["make"]
			if make == "def":
				make = ""
			print "# --- %s"%make
			aobj = lRig.Leg(make)
			aobj.create()
			aobj.create(1)
			return aobj
		except:
			traceback.print_exc()
		return
	def btn_importSpineTemp(self,prefixTfd=""):
		reload(bTemp)
		prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		bTemp.importSpineTemplate(prefix)
		return
	
	def btn_refreshSpineTemp(self,prefixTfd,jotNum,ctrlNum):
		reload(bTemp)
		prefix= prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		
		jn = mc.intSliderGrp(jotNum,q=True,v=True)
		cn = mc.intSliderGrp(ctrlNum,q=True,v=True)
		bTemp.refreshShineTemplate(prefix=prefix,number=cn)
		return
	
	def btn_createSpine(self,prefixTfd,sMode,sjotNumber):
		reload(sRig)
		prefix = prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		if type(sMode) == "string":
			sm = mc.optionMenu(sMode, q=True, sl=True)
		else:sm = sMode
		jn = mc.intSliderGrp(sjotNumber,q=True,v=True)

		tmpdata = sRig.Spine(prefix, "").getTemplateDate()
		try:
			make = tmpdata["make"]
			if make == "def":
				make = ""

			# print "# --- %s" % make
			sobj = sRig.Spine(make,"")
			if sm == 1:
				sobj.fkSpine(tmpdata,jotNumber=jn)
			elif sm == 2:
				sobj.sampleFk(tmpdata,)
			elif sm == 3:
				sobj.nurbsFk(tmpdata,jotNumber=jn)
			return sobj
		except:
			traceback.print_exc()
		return
	
	def btn_importNeckTemp(self,prefixTfd=""):
		prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		bTemp.importSpineTemplate(prefix,bc.gNeck)
		return
	
	def btn_refreshNeckTemp(self,prefixTfd,jotNum,ctrlNum):
		prefix=prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)

		jn = mc.intSliderGrp(jotNum,q=True,v=True)
		cn = mc.intSliderGrp(ctrlNum,q=True,v=True)
		bTemp.refreshShineTemplate(prefix=prefix,number=cn,tag=bc.gNeck)
		return

	def btn_createNeck(self, prefixTfd,sMode=0,sjotNumber=0):
		
		reload(nRig)
		
		prefix = prefixTfd
		if prefixTfd:
			prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)
		
		if type(sMode) == "string":
			sm = mc.optionMenu(sMode, q=True, sl=True)
		else: sm = sMode

		jn = mc.intSliderGrp(sjotNumber,q=True,v=True)
		
		tmp = nRig.Neck(prefix, "").getTemplateDate()

		try:
			make = tmp["make"]
			if make == "def":
				make = ""
	
			# print "# --- %s" % make
	
			if sm == 1:
				nobj = nRig.Neck(make, "")
				nobj.fkSpine(tmp,  jotNumber=jn)
			elif sm == 2:
				nobj = nRig.Neck(make, "")
				nobj.sampleFk(tmp, )
			elif sm == 3:
				nobj = nRig.Neck(make, "")
				nobj.nurbsFk(tmp, jotNumber=jn)
			return nobj
		except:
			traceback.print_exc()
		return
	
	def autoLayout(self):
		column = mc.columnLayout(adj=True)
		
		mc.button(l = "Import Body Template",c = lambda *args:self.btn_importBodyTemplate())
		mc.separator()
		
		mc.frameLayout(l="Refresh Spine Span")
		sintsj = mc.intSliderGrp(l="Skin joint",f=True,v=5)
		sintcs = mc.intSliderGrp(l="control span", f=True,v=3)
		mc.separator()
		mc.button(l="Refresh",c=lambda *args:self.btn_refreshSpineTemp("",sintsj,sintcs,))
		mc.separator()
		mc.setParent("..")
		
		mc.frameLayout(l="Refresh Spine Span")
		nintsj = mc.intSliderGrp(l="Skin joint",f=True,v=5)
		nintcs = mc.intSliderGrp(l="control span", f=True,v=3)
		mc.separator()
		mc.button(l="Refresh",c=lambda *args:self.btn_refreshNeckTemp("",nintsj,nintcs))
		mc.separator()
		mc.setParent("..")
		
		mc.button(l="Create ...", c = lambda *args:self.btn_autoBodyCreate(sintsj,nintsj),
				  bgc=editor.Editor().rgbConvert(220, 185, 103))
		mc.separator()
		mc.button(l="Update ...", c=lambda *args: self.btn_update(),
				  bgc=editor.Editor().rgbConvert(112, 128, 144))
		# mc.button(l="Update ... (2019/06/24)",c=lambda *args:self.btn_update_20190624())
		# mc.button(l="Fix Noroll ... (2019/06/24)",c=lambda *args:self.btn_fixNoroll())
		# mc.button(l="Update ... (2019/10/14)",c=lambda *args:self.btn_update_20191014())

		mc.button(l="fingerDriverKey",c=lambda *args:self.btn_fingerDriverKey())

		mc.setParent("..")
		return column
	
	def btn_update(self):
		self.btn_update_20190520()
		self.btn_update_20190624()
		self.btn_fixNoroll()
		self.btn_update_20191014()
		return
	
	def btn_importBodyTemplate(self):
		reload(bTemp)
		bTemp.importBodyTemplate()
		bTemp.refreshShineTemplate("",number=5,)
		bTemp.refreshShineTemplate("",number=3,tag=bc.gNeck)
		
		print "{} : Import template. ({}) ".format(self.__class__.__name__,
												   bTemp.__version__)
		
		return
	
	def btn_autoBodyCreate(self,spineJotNum,neckJotNum):
		reload(aRig)
		reload(lRig)
		reload(sRig)
		reload(nRig)
		reload(fRig)
		
		sJotNum = mc.intSliderGrp(spineJotNum,q=True,v=True)
		nJotNum = mc.intSliderGrp(neckJotNum,q=True,v=True)
		
		try:
			om.MGlobal.displayInfo(" - Auto rig - (v2.1.14)")
			sobj = self.btn_createSpine("",1,spineJotNum)
			
			hip_ctr = crc.objToControl(sobj.in_flw,name=con.lname(bc.gHip),scale=5,colorId=13,ctrlShape="cube")
			hip_jot = mc.createNode(nc.tJoint,name=con.lname(bc.gHip,sc.sJot),parent = hip_ctr)
			mc.setAttr(hip_jot+".ty",-0.1)
			body_ctr = crc.objToControl(sobj.in_flw,name=con.lname(bc.gBody),scale=5,colorId=13)
			body_master_ctr = crc.objToControl(sobj.in_flw,name=con.lname(bc.gBody,"master"),scale=7,colorId=17)
			mc.parent(hip_ctr,body_ctr)
			mc.parent(body_ctr,body_master_ctr)
			mc.parent(body_master_ctr,sobj.globalCtr)
			[con.emptyGroup(_) for _ in [hip_ctr,body_ctr,body_master_ctr]]
			body_loc = con.objToLocator(body_ctr,name=con.lname(bc.gBody))
			mc.parentConstraint(body_loc,sobj.localGrp,mo=True)
			# --- arm
			laobj = aRig.Arm("")
			laobj.create()
			raobj = aRig.Arm("")
			raobj.create(1)
			mc.parentConstraint(sobj.out_flw,laobj.localGrp,mo=True)
			mc.parentConstraint(sobj.out_flw,raobj.localGrp,mo=True)
			# --- leg
			llobj = lRig.Leg("")
			llobj.create()
			rlobj = lRig.Leg("")
			rlobj.create(1)
			mc.parentConstraint(hip_jot,llobj.localGrp,mo=True)
			mc.parentConstraint(hip_jot,rlobj.localGrp,mo=True)
			# --- neck
			nobj = self.btn_createNeck("",1,neckJotNum)
			mc.parentConstraint(sobj.out_flw,nobj.localGrp,mo=True)
			
			om.MGlobal.displayInfo(" - Complate - ")
		except:
			traceback.print_exc()
		
		mc.select(cl=True)
		return
	
	def btn_update_20190520(self):
		
		print "+----------------------------"

		
		# control visibility
		for ctr in mc.ls("*_ctrl"):
			mc.setAttr(ctr+".v",l=True,k=False,cb=False)
			
		print "Visibility attribute 0."

		# Rotation Order
		
		onRotateOrder_list = [
			"Head_ctrl",
			"Neck_ctrl",
			"Spine_Master_ctrl",
			"Spine_Body_ctrl",
			"Spine_Hip_ctrl",
			"L_Arm_Ik_ctrl",
			"R_Arm_Ik_ctrl",
			"L_Leg_Ik_ctrl",
			"R_Leg_Ik_ctrl",
			"L_Leg_Thigh_ctrl",
			"R_Leg_Thigh_ctrl",
			"L_Arm_Fk_Arm_ctrl",
			"R_Arm_Fk_Arm_ctrl",
			"L_Arm_Fk_Wrist_ctrl",
			"R_Arm_Fk_Wrist_ctrl"
		]
		
		for oro in onRotateOrder_list:
			mc.setAttr(oro+".rotateOrder",k=True)
		
		print "RotateOrder attribute 1."
		# adjust existed align
		
		existAlian_list = [
			"L_Arm_Fk_Arm_global_loc",
			"R_Arm_Fk_Arm_global_loc",
			"L_Leg_Fk_Leg_global_loc",
			"R_Leg_Fk_Leg_global_loc",
		]
		
		for ea in existAlian_list:
			grp = mc.group(ea, name = con.lname(ea, "adjust"))
			mc.parent(grp,"global_ctrl")
		
		print "Adjust existed align 1."
		# add new align
		
		addAlign_list = [
			"Head_ctrl",
			"Neck_ctrl",
		]

		for aa,attr in zip(addAlign_list,[gNeck,gChest]):
			
			hook = bCore.BodyCore().followHook(aa,fowAttr=(aGlobal,attr))
			mc.parent(hook[attr], "%s_ctrl"%attr)
			
			con.transferAttr(hook[gBridge], aa, (aFollow,))
			# mc.parentConstraint(hook["out"],aa+"_Con",mo=True)
			# mc.pointConstraint(hook["out"],aa+"_Con",mo=True)
			if mc.objExists(aa+"_Con_orientConstraint1"):
				mc.delete(aa+"_Con_orientConstraint1")
			mc.orientConstraint(hook["out"],aa+"_Con",mo=True)
		
			mc.parent(hook[gBridge],aa+"_Zero")
			mc.parent(hook[aGlobal],"global_ctrl")
			
			
		print "Add new align 1."
		
		# add sec rotate
		secRot0_list = [
			"L_Arm_Sec_0_Target*_rot",
			"R_Arm_Sec_0_Target*_rot",
			
			"L_Leg_Sec_0_Target*_rot",
			"R_Leg_Sec_0_Target*_rot",
		]

		secRot1_list = [
			"L_Arm_Sec_1_Target*_rot",
			"R_Arm_Sec_1_Target*_rot",
	
			"L_Leg_Sec_1_Target*_rot",
			"R_Leg_Sec_1_Target*_rot",
		]
		
		secCtrl_list = [
			"L_Arm_Twist*_ctrl",
			"R_Arm_Twist*_ctrl",
			"L_Leg_Twist*_ctrl",
			"R_Leg_Twist*_ctrl"
		]
		
		for sc in secCtrl_list:
			_sc = mc.ls(sc, fl=True)
			for _s in _sc:
				con.lockHideAttr(_s, ["rx", "rz", "sx", "sy", "sz", "v"])
		
		for i,sr in enumerate(secRot0_list):
			_sr_list = mc.ls(sr,fl=True)
			_sc_list = mc.ls(secCtrl_list[i], fl=True)
			for x,_sr in enumerate(_sr_list):
				_incnt = mc.listConnections(_sr+".ry",s=True,d=False)[0]
				incnt = mc.listConnections(_incnt, s=True, d=False)
				radio = mc.getAttr(incnt[0]+".ratio")

				incntPma = mc.createNode(tPlusMinusAverage, name = con.lname(_sr, sPma))
				mc.connectAttr(incnt[0] + ".rotation",incntPma+".i1[0]")
				mc.connectAttr(incntPma+".o1",_sr+".ry",f=True)
				
				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[0]+".ry",radioMd+".i1x")
				mc.setAttr(radioMd+".i2x",1-radio)
				mc.connectAttr(radioMd+".ox",incntPma+".i1[1]")

				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[2] + ".ry", radioMd + ".i1x")
				mc.setAttr(radioMd + ".i2x", radio)
				mc.connectAttr(radioMd + ".ox", incntPma + ".i1[2]")
				
				if x == 3:
					value = radio*2 - 1
				elif x == 4:
					value = radio - 1
				else:
					value = radio * 2
					
				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[1] + ".ry", radioMd + ".i1x")
				mc.setAttr(radioMd + ".i2x", value)
				mc.connectAttr(radioMd + ".ox", incntPma + ".i1[3]")
				
				if "R_" in _sr:
					con.insertNeg(incntPma, "i1[1]")
					con.insertNeg(incntPma, "i1[2]")
					con.insertNeg(incntPma, "i1[3]")
				
		for i, sr in enumerate(secRot1_list):
			_sr_list = mc.ls(sr, fl=True)
			_sc_list = mc.ls(secCtrl_list[i], fl=True)
			for x, _sr in enumerate(_sr_list):
				_incnt = mc.listConnections(_sr + ".ry", s=True, d=False)[0]
				incnt = mc.listConnections(_incnt, s=True, d=False)
				radio = mc.getAttr(incnt[0] + ".ratio")
		
				incntPma = mc.createNode(tPlusMinusAverage, name=con.lname(_sr, sPma))
				mc.connectAttr(incnt[0] + ".rotation", incntPma + ".i1[0]")
				mc.connectAttr(incntPma + ".o1", _sr + ".ry", f=True)
		
				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[2] + ".ry", radioMd + ".i1x")
				mc.setAttr(radioMd + ".i2x", 1 - radio)
				mc.connectAttr(radioMd + ".ox", incntPma + ".i1[1]")
		
				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[4] + ".ry", radioMd + ".i1x")
				mc.setAttr(radioMd + ".i2x", radio)
				mc.connectAttr(radioMd + ".ox", incntPma + ".i1[2]")
		
				if x == 3:
					value = radio * 2 - 1
				elif x == 4:
					value = radio - 1
				else:
					value = radio * 2
		
				radioMd = mc.createNode(tMultiplyDivide, name=con.lname(_sr, sMd))
				mc.connectAttr(_sc_list[3] + ".ry", radioMd + ".i1x")
				mc.setAttr(radioMd + ".i2x", value)
				mc.connectAttr(radioMd + ".ox", incntPma + ".i1[3]")
				
				if "R_" in _sr:
					con.insertNeg(incntPma, "i1[1]")
					con.insertNeg(incntPma, "i1[2]")
					con.insertNeg(incntPma, "i1[3]")
		
		print "Add second control rotate 1."
		mc.addAttr("Chest_ctrl",ln="chest_breathe",at="float",dv=0,max=10,min=-10,k=True)
		mc.addAttr("Chest_ctrl",ln="belly_breathe",at="float",dv=0,max=10,min=-10,k=True)

		print "SetAttr Constraint interpType 2."
		sel = mc.ls(type="parentConstraint")+mc.ls(type="orientConstraint")
		for sl in sel:
			mc.setAttr(sl + ".interpType", 2)
		#setAttr "L_Arm_Twist1_ctrl_Con_aimConstraint1.worldUpType" 3;
		for lr in ["L","R"]:
			for tag in ["Arm","Leg"]:
				for i in [1,3]:
					ctr = "%s_%s_Twist%s_ctrl"%(lr,tag,i)
					mc.parent(ctr+"_Sdk",ctr+"_Zero")
					mc.setAttr(ctr+"_Con_aimConstraint1.worldUpType",3)
					mc.parent(ctr+"_Sdk",ctr+"_Con")


		print "+----------------------------"

		mc.select(cl=True)
		return
	def btn_fingerDriverKey(self):
		prefix = "R"
		control = "%s_armA_palm_ctrl"%prefix
		con.lockHideAttr(control, ["sx", "sy", "sz", "v"])
		loc = con.objToLocator(control, name=con.lname(control, "out"))
		con.addEmptyGroup(loc, ["Zero"])
		
		finger =[
			"%s_Finger_Index1_ctrl"%prefix,
			"%s_Finger_Middle1_ctrl"%prefix,
			"%s_Finger_Ring1_ctrl"%prefix,
			"%s_Finger_Pinky1_ctrl"%prefix,
		]
		pro = 1./(len(finger))
		for i,f in enumerate(finger):

			trans = con.objToLocator(f + "_Con", name=con.lname(f, "trans"))
			pac = mc.parentConstraint("%s_Arm_Dr_Wrist"%prefix,loc,trans,mo=True)[0]
			mc.setAttr(pac+".%s_Arm_Dr_WristW0"%prefix,1-i*pro+pro)
			mc.setAttr(pac+"."+loc+"W1",i*pro+pro)
			
			mc.connectAttr(trans+".t",f+"_FD.t")
			mc.connectAttr(trans+".r",f+"_FD.r")
			
			fMd = mc.createNode(tMultiplyDivide, name=con.lname(f, sMd))
			mc.connectAttr(trans+".r",fMd+".i1")
			mc.setAttr(fMd+".i2",2,2,2)
			mc.connectAttr(fMd+".o",f.replace("1_","2_")+"_Con.r",f=True)
			
			gg = con.addEmptyGroup(f.replace("1_", "2_"), ["cnt"])
			gmd = mc.createNode(tMultiplyDivide, name=con.lname(gg, sMd))
			
			mc.connectAttr(fMd+".oy",gmd+".i1x")
			mc.setAttr(gmd+".i2x",i*pro*3)
			mc.connectAttr(gmd+".ox",gg[0]+".rz")
			
			
		return
	
	def btn_update_20190624(self):
		
		for tp in ["orientConstraint","parentConstraint"] :
			for i in  mc.ls(typ=tp):
				mc.setAttr(i+".interpType",2)
		mc.parent("R_Leg_Ikhanle_stretch_loc", "R_Leg_Toe_pivot")
		mc.parent("L_Leg_Ikhanle_stretch_loc", "L_Leg_Toe_pivot")
		
		return
	def btn_update_20191014(self):
		
		mc.parent("Head_ctrl_Neck_loc","Neck1_ctrl")
		mc.parent("Chest_jot_loc","Chest_jot_Zero")
		mc.parent("Head_jot_loc","Head_jot_Zero")
		value = mc.xform("Chest_jot",q=True,ws=True,t=True)[1]
		mc.setAttr("Head_jot_loc.ty",value*0.01)
		mc.setAttr("Chest_jot.ty",value*0.01)
		mc.setAttr("Spine_Hip_jot.ty",value*-0.01)
		return
	def btn_fixNoroll(self):
		
		for lr in [gLeft,gRight]:
			for al in [gArm,gLeg]:
				for so in ["star","out"]:
					for k in ["Sec_0_Target","Sec_1_Target","Wrist","Ankle"]:
						key = con.lname(k, "noroll")
						skey = con.lname(lr, al, key, so, )
						spc = con.lname(skey, "parentConstraint1")
						if not mc.objExists(spc):
							continue
						stgt = mc.parentConstraint(con.lname(skey, "parentConstraint1"), q=1, tl=1)[0]
						sloc = con.objToLocator(skey, name=con.lname(skey, "fix"))
						mc.parent(sloc,stgt)
						if so == "star":
							mc.parent(skey,sloc)
						mc.delete(spc)
						mc.parentConstraint(sloc,skey,mo=True)
				
				
				
		a = "L_Arm_Sec_0_Target_noroll_star"
		b = "L_Arm_Sec_0_Target_noroll_out"
		
		
		mc.parentConstraint("R_Arm_Sec_0_Target_noroll_out_parentConstraint1", q=1, tl=1)
		return
	
	def btn_importFingerTemplate(self,prefixTfd,checklist,toe=False):
		prefix = mc.textFieldGrp(prefixTfd,q=True,tx=True)

		for i,check in enumerate(checklist):
			if mc.checkBox(check,q=True,v=True):
				cn = mc.checkBox(check,q=True,l=True)
				lfinger = cn
				if toe:
					lfinger = gToe + cn
				bTemp.importFingerTemplate(prefix,tag=lfinger,saxial=i)
		
		return
	def btn_createFingger(self,checklist,fMode,toe=False):
		reload(fRig)
		
		lfinger = gFinger
		if toe:
			lfinger = gToe+gFinger
		# tmpData = fRig.Finger("","",).parsePartTemplate()
		# print(tmpData)
		for i,check in enumerate(checklist):
			if mc.checkBox(check,q=True,v=True):
				cn = mc.checkBox(check,q=True,l=True)
				lcn = cn
				if toe:
					lcn =  gToe + cn
				tmpData = fRig.Finger("", "", lcn+gFinger).parsePartTemplate()[0]
				make = tmpData["make"]
				if make == "def":
					make = ""
				fRig.Finger(make, gLeft, gFinger).create(tmpData,cn)
		return
	
	
	
def showEditor():
	BodyRigEditor().editor()
	return
if __name__ == '__main__':
	pass